import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';
import prompt from '@system.prompt';
import FFA from '@ohos.file.fileAccess'

let uris = [];

export default class EntryAbility extends UIAbility {
    async eachFileInfo(fileInfo: FFA.FileInfo){
        let fileInfoTemp = fileInfo;
        let isDone = false;
        while (!isDone) {
            let relativePath = fileInfoTemp.relativePath;
            let fileName = fileInfoTemp.fileName;
            let uri = fileInfoTemp.uri;
            uris.push(uri);
            let mode = fileInfoTemp.mode;
            let mimeType = fileInfoTemp.mimeType;
            let fit = fileInfoTemp.listFile();
            let next = fit.next();
            isDone = next.done;
            fileInfoTemp = next.value;
        }
    }
    async eachRootInfo(rootInfo: FFA.RootInfo){
        let fileInfos = [];
        let isDone = false;
        try {
            let fileIterator = rootInfo.listFile();
            if (!fileIterator) {
                console.error("listFile interface returns an undefined object");
                return;
            }
            while (!isDone) {
                let next = fileIterator.next();
                console.log("next result = " + JSON.stringify(next));
                let str = JSON.stringify(next);
                isDone = next.done;
                if (!isDone){
                    let uri = next.value.uri;
                    let relativePath = next.value.relativePath;
                    let mimeType = next.value.mimeType;
                    let fileName = next.value.fileName;
                    this.eachFileInfo(next.value)
                    uris.push(uri)
                    fileInfos.push(next.value);

                }
            }
        } catch (error) {
            console.error("listFile failed, errCode:" + error.code + ", errMessage:" + error.message);
        }
    }


    async GetList(){
        try {
            let ctx = this.context;
            let fa  = FFA.createFileAccessHelper(ctx);
            let wants = await FFA.getFileAccessAbilityInfo()
            let fileAcsHelper = FFA.createFileAccessHelper(ctx, wants)
            // 获取设备根节点信息
            const rootIterator: FFA.RootIterator = await fileAcsHelper.getRoots()
            let rootInfoArr = [];
            let next = rootIterator.next();
            let isDone = next.done;
            while (!isDone) {
                const rootInfo: FFA.RootInfo = next.value;
                let uri = rootInfo.uri;
                let deviceType = rootInfo.deviceType;
                let relativePath = rootInfo.relativePath;
                let displayName = rootInfo.displayName;
                uris.push(uri)
                await this.eachRootInfo(rootInfo);
                rootInfoArr.push(rootInfo);
                next = rootIterator.next();
                isDone = next.done;
            }
        } catch (err) {
            let a = 1;
        } finally {
            let a = 1;
        }
    }

    async StartTest(){

        await this.GetList();

        try{
            let ctx = this.context;
            let uid = globalThis.parentUid;

            // @ts-ignore
            let fa  = FFA.createFileAccessHelper(ctx);
            prompt.showToast({
                message:"2"
            });
            let str = await fa.getDefaultSavePath(uid);
            let path = uris[uris.length-1];//"file://com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon";

            let isExist = await fa.access(path+"/testDir1");
            let newDir = path+"/testDir1";
            if(!isExist) {
                newDir = await fa.mkDir(path, "testDir1");
            }
            await fa.setDefaultSavePath(uid, "file://com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon");
            //let res = await fa.setDefaultSavePath(uid, newDir);
            let result = await fa.getDefaultSavePath(uid);
            prompt.showToast({
                message:"result:"+ uid + ","+result
            });
        }catch (e){
            let a = e;
        }
    }

    onCreate(want, launchParam) {
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');

        globalThis.parentUid = want.parameters.uid;
        if (!globalThis.parentUid)
        {
            globalThis.parentUid = 124567;
        }
        globalThis.uriParam = want.parameters.uri;
        hilog.info(0x0000, 'testTag', '%{public}s, %{public}d', 'Ability wanguid', want.parameters.uid);

        this.StartTest();




    }

    onDestroy() {
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
    }

    onWindowStageCreate(windowStage: window.WindowStage) {
        // Main window is created, set main page for this ability
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

        windowStage.loadContent('pages/Index', (err, data) => {
            if (err.code) {
                hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                return;
            }
            hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
        });
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
    }

    onForeground() {
        // Ability has brought to foreground
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
    }

    onBackground() {
        // Ability has back to background
        hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
    }
}
